"""
仿射变换：平移，旋转
"""
import cv2
import numpy as np

# 平移
def translate(img,x,y):
    """
    平移
    :param img: 要平移的图像
    :param x: 水平方向平移的像素
    :param y: 垂直方向平移的像素
    :return: 平移后的图像
    """
    # 构建平移矩阵
    M = np.float32([[1,0,x],
                 [0,1,y]])
    # 获取高度，宽度
    h,w = img.shape[:2]
    # 平移
    res = cv2.warpAffine(img,M,(w,h))

    return res

# 旋转
def rotate(img,angle,center=None):
    h,w = img.shape[:2]
    if center is None:
        center = (w/2,h/2)

    # 生成旋转矩阵
    M = cv2.getRotationMatrix2D(center,angle,1.0)
    res = cv2.warpAffine(img,M,(w,h))

    return res


if __name__ == '__main__':
    img = cv2.imread('../data/lena.jpg')
    cv2.imshow('img',img)
    # 平移
    # res = translate(img,0,50) # y为正数，为向下移动，x为正数，为向右移动
    # cv2.imshow('img_y50',res)
    # res1 = translate(img,-50,50)
    # cv2.imshow('img1',res1)

    # 旋转
    res = rotate(img,45) #  正数为逆时针
    cv2.imshow('rotate_45',res)
    res1 = rotate(img,-90)
    cv2.imshow('rotate_-90',res1)


    cv2.waitKey()
    cv2.destroyAllWindows()